<template>
    <div class="content-wrapper-view">
		<div class="content-wrapper-body"><!-- 开始 -->

        <div class="filter-wrapper">
            <el-form ref="filterForm" :model="listQuery" :inline="true">
                <el-form-item prop="name" size="medium">
                    <el-input v-model="listQuery.name" placeholder="名称"></el-input>
                </el-form-item>

                <el-form-item prop="status" size="medium">
                    <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 100px">
                        <el-option
                                v-for="item in statusOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="orderBy" size="medium">
                    <el-select v-model="listQuery.orderBy" placeholder="排序" style="width: 120px">
                        <el-option
                                v-for="item in sortOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
                <el-button type="primary" size="medium" icon="el-icon-plus" @click="handleCreate">添加</el-button>
                <el-button type="danger" size="medium" icon="el-icon-delete" @click="handleBatchDelete">删除</el-button>
            </el-form>

        </div>

        <el-table
                :data="list"
                border fit
                highlight-current-row
                v-loading="listLoading"
                element-loading-text="给我一点时间"
                @selection-change="handleSelectionChange">

            <el-table-column
                    type="selection"
                    width="55" align="center">
            </el-table-column>
            <el-table-column type="index" width="55" align="center"></el-table-column>


            <el-table-column label="关键字" width="300px" align="center">
                <template slot-scope="scope"> {{scope.row.keyword}} </template>
            </el-table-column>

            <el-table-column label="回复内容" min-width="300px" align="center">
                <template slot-scope="scope"> {{scope.row.reply}} </template>
            </el-table-column>

            <el-table-column label="关联内容" align="center">
                <template slot-scope="scope">
                    <el-tag type="primary" v-if="scope.row.templateType === 'text'">文本内容</el-tag>
                    <el-tag type="primary" v-if="scope.row.templateType === 'article'">单图文内容</el-tag>
                    <el-tag type="primary" v-if="scope.row.templateType === 'articles'">多图文内容</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="状态" width="80px" align="center">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.status === 1">正常</el-tag>
                    <el-tag type="danger" v-else>禁用</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="最后修改时间" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.utime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
            </el-table-column>

            <el-table-column label="操作" width="350px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="el-icon-view" v-if="scope.row.templateType && scope.row.templateId" @click="openContentDetailDialog(scope.row)"></el-button>
                    <el-tooltip content="未关联内容" placement="top" v-else>
                        <el-button size="small" type="warning" icon="el-icon-view"></el-button>
                    </el-tooltip>
                    <el-button size="small" type="primary" icon="edit" @click="handleAssignDialog(scope.row)">关联内容</el-button>
                    <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleDialogClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="名称" prop="keyword">
                    <el-input v-model="form.keyword" style="width: 400px;"></el-input>
                </el-form-item>

                <el-form-item label="模板类型">
                    <el-select
                            clearable
                            v-model="form.templateType"
                            placeholder="请选择"
                            @change="handleChangeTemplate"
                            style="width: 400px">
                        <el-option
                                v-for="item in templateTypeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="回复内容" style="width: 520px;">
                    <el-input
                            :disabled="contentDisabled"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="form.reply">
                    </el-input>
                </el-form-item>

                <el-form-item label="状态" style="width: 300px;">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="2">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>


                <el-form-item>
                    <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">提 交</el-button>
                    <el-button v-else="" type="primary" @click="update">提 交</el-button>
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="关联内容" :visible.sync="dialogFormVisibleContent" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleDialogCloseContent">

            <div class="filter-wrapper">
                <el-form ref="filterFormContent" :model="listQueryContent" :inline="true">
                    <el-form-item prop="title" size="medium">
                        <el-input v-model="listQueryContent.title" placeholder="标题"></el-input>
                    </el-form-item>

                    <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilterContent">搜索</el-button>
                    <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilterContent">重置</el-button>
                </el-form>
            </div>

            <el-table
                    :data="listContent"
                    border fit
                    highlight-current-row
                    v-loading="listLoadingContent"
                    @row-click="handleClickRowTemplate"
                    element-loading-text="给我一点时间">

                <el-table-column
                        type="selection"
                        width="55" align="center">
                </el-table-column>
                <el-table-column type="index" width="55" align="center"></el-table-column>


                <el-table-column label="标题" align="center">
                    <template slot-scope="scope"> {{scope.row.title}} </template>
                </el-table-column>

            </el-table>

            <div v-show="!listLoadingContent" class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChangeContent"
                        @current-change="handleCurrentChangeContent"
                        :current-page="listQueryContent.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="listQueryContent.rows"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalContent">
                </el-pagination>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibleContent = false">取 消</el-button>
                <el-button type="primary" @click="handleAssign">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="contentTitle" :visible.sync="dialogDetailVisibleContent"  @close="handleDialogCloseDetailContent">
            <div class="content" v-html="contentDetail.content"></div>
        </el-dialog>

        <el-dialog title="图文列表" :visible.sync="dialogGroupArticleListVisible">
            <el-table
                    :data="groupArticleList"
                    border fit
                    highlight-current-row
                    v-loading="listArticleLoadingDialog"
                    element-loading-text="给我一点时间">

                <el-table-column type="index" width="55" align="center"></el-table-column>

                <el-table-column label="标题" align="left">
                    <template slot-scope="scope"> {{scope.row.article.title}} </template>
                </el-table-column>

            </el-table>
        </el-dialog>
    </div>
    </div>
</template>

<script>
    import { created, updated, deleted, deletedBatch, selectOne, selectList, updateTemplate } from '@/api/weixin/keyword'
    import { selectOne as selectOneText, selectList as selectTextList } from '@/api/weixin/text'
    import { selectOne as selectOneArticle, selectList as selectArticleList } from '@/api/weixin/article'
    import { selectByGroupId as selectOneArticleGroup, selectList as selectArticlesList } from '@/api/weixin/articleGroup'

    const sortOptions= [{label: '升序', key: 'ctime asc'}, {label: '降序', key: 'ctime desc'}]
    const statusOptions = [{label: '正常', key: 1}, {label: '禁用', key: 2}]

    const templateTypeOptions = [
        {value: 'text', label: '文本消息'},
        {value: 'article', label: '单图文消息'},
        {value: 'articles', label: '多图文消息'}
    ]

    export default {
        name: 'Keyword',
        data() {
            return {
                list: [],
                listContent: [],
                total: null,
                totalContent: null,
                listLoading: false,
                listLoadingContent: false,
                multipleSelection: [],
                listQuery: {
                    page: 1,
                    rows: 10,
                    keyword: undefined,
                    orderBy: 'ctime desc'
                },
                listQueryContent: {
                    page: 1,
                    rows: 10,
                    title: undefined,
                    orderBy: 'ctime desc'
                },
                dialogFormVisibleContent: false,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '创建'
                },
                statusOptions,
                sortOptions,
                templateTypeOptions,
                form: {
                    keyword: null,
                    status: 1,
                    reply: null
                },
                rules: {
                    keyword: [
                        { required: true, message: '请输入应用名称', trigger: 'blur' }
                    ]
                },
                contentDisabled: false,
                templateType: null,

                dialogDetailVisibleContent: false,
                dialogGroupArticleListVisible: false,
                listArticleLoadingDialog: false,
                groupArticleList: [],
                contentTitle: null,
                contentDetail: {
                    title: null,
                    content: null
                }
            }
        },
        created() {
            this.getTableData()
        },
        methods: {
            handleDialogCloseDetailContent() {
                this.contentTitle = null
                this.contentDetail = {
                    title: null,
                    content: null
                }
            },
            openContentDetailDialog(row) {

                if(row.templateType === 'text') {
                    this.dialogDetailVisibleContent = true
                    selectOneText(row.templateId).then(response => {
                        let data = response.data
                        this.contentTitle = '文本内容 - '+data.title
                        this.contentDetail.title = data.title
                        this.contentDetail.content = data.content
                    })
                } else if(row.templateType === 'article') {
                    this.dialogDetailVisibleContent = true
                    selectOneArticle(row.templateId).then(response => {
                        let data = response.data
                        this.contentTitle = '单图文内容 - '+data.title
                        this.contentDetail.title = data.title
                        this.contentDetail.content = data.articleTxt.txt
                    })
                } else if(row.templateType === 'articles') {
                    this.dialogGroupArticleListVisible = true
                    this.listLoadingDialog = true
                    selectOneArticleGroup(row.templateId).then(response => {
                        this.groupArticleList = response.data
                        this.listArticleLoadingDialog = false
                    }).catch(error => {
                        console.log(error)
                        this.listLoadingDialog = false
                    })
                }
            },
            handleFilterContent() {//条件过滤
                this.listQueryContent.page = 1

                if(this.templateType === 'text') {
                    this.getTextTableData()
                } else if(this.templateType === 'article') {
                    this.getArticleTableData()
                } else if(this.templateType === 'articles') {
                    this.getArticleTableData()
                }
            },
            handleResetFilterContent() {//重置过滤条件
                this.$refs.filterFormContent.resetFields()

                if(this.templateType === 'text') {
                    this.getTextTableData()
                } else if(this.templateType === 'article') {
                    this.getArticleTableData()
                } else if(this.templateType === 'articles') {
                    this.getArticlesTableData()
                }
            },
            handleSizeChangeContent(val) {
                this.listQueryContent.rows = val
                if(this.templateType === 'text') {
                    this.getTextTableData()
                } else if(this.templateType === 'article') {
                    this.getArticleTableData()
                } else if(this.templateType === 'articles') {
                    this.getArticlesTableData()
                }
            },
            handleCurrentChangeContent(val) {
                this.listQueryContent.page = val
                if(this.templateType === 'text') {
                    this.getTextTableData()
                } else if(this.templateType === 'article') {
                    this.getArticleTableData()
                } else if(this.templateType === 'articles') {
                    this.getArticlesTableData()
                }
            },
            handleClickRowTemplate(row) {
                this.form.templateId = row.id
            },
            handleAssign() {
                this.dialogFormVisibleContent = false

                delete this.form.status
                updateTemplate(this.form).then(response => {
                    if(response.data.status) {
                        this.$notify({
                            title: '成功', message: response.data.message,
                            type: 'success', duration: 2000
                        })
                        this.getTableData()
                    } else {
                        this.$notify({
                            title: '发生错误', message: response.data.message,
                            type: 'error', duration: 2000
                        })
                    }
                })
            },
            handleAssignDialog(row) {
                this.dialogFormVisibleContent = true
                this.templateType = row.templateType
                this.form.id = row.id

                if(row.templateType === 'text') {
                    this.getTextTableData()
                } else if(row.templateType === 'article') {
                    this.getArticleTableData()
                } else if(row.templateType === 'articles') {
                    this.getArticlesTableData()
                }
            },
            getTextTableData() {
                this.listLoadingContent = true
                selectTextList(this.listQueryContent).then(response => {
                    this.listContent = response.data.data.list
                    this.totalContent = response.data.data.total
                    this.listLoadingContent = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },
            getArticleTableData() {
                this.listLoadingContent = true
                selectArticleList(this.listQueryContent).then(response => {
                    this.listContent = response.data.data.list
                    this.totalContent = response.data.data.total
                    this.listLoadingContent = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },
            getArticlesTableData() {
                this.listLoadingContent = true
                selectArticlesList(this.listQueryContent).then(response => {
                    this.listContent = response.data.data.list
                    this.totalContent = response.data.data.total
                    this.listLoadingContent = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },
            handleDialogCloseContent() {//关闭窗口回调函数
                this.listContent = null
                this.totalContent = null
            },

            handleChangeTemplate(value) {
                if(value !== '') {
                    this.form.reply = ''
                    this.contentDisabled = true
                } else {
                    this.contentDisabled = false
                }
            },
            handleFilter() {//条件过滤
                this.listQuery.page = 1
                this.getTableData()
            },
            handleResetFilter() {//重置过滤条件
                this.$refs.filterForm.resetFields()
                this.getTableData()
            },
            handleDialogClose() {//关闭窗口回调函数
                this.resetForm()
                this.contentDisabled = false
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getTableData()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getTableData()
            },
            handleCreate() {//添加数据窗口
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {//修改数据窗口
                selectOne(row.id).then(response => {
                    this.dialogStatus = 'update'
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                    if(this.form.templateType) {
                        this.contentDisabled = true
                    }
                })
            },
            handleDelete(row) {//删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getTableData()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'warning', message: '已取消删除' })
                })
            },
            handleBatchDelete() {//批量删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(this.multipleSelection.length > 0) {
                        let ids = []
                        for(let item of this.multipleSelection) {
                            ids.push(item.id)
                        }
                        deletedBatch({ids: ids.join(',')}).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })

                    } else {
                        this.$notify({
                            title: '提示', message: '请选择需要删除的记录',
                            type: 'warning', duration: 2000
                        })
                    }
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {//添加数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.handleResetFilter()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            update() {//修改数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            getTableData() {
                this.listLoading = true
                selectList(this.listQuery).then(response => {
                    this.list = response.data.data.list
                    this.total = response.data.data.total
                    this.listLoading = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },
            resetForm() {//重置表单
                this.$refs['form'].resetFields()
                this.form = {
                    name: '',
                    status: 1,
                    reply: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .content{
        min-width: 100%;
        word-wrap:break-word;
        max-height: 500px;
        overflow: auto;
    }
</style>
